/**
 * 全局编辑表单容器配置
 * @author luguoxiang
 * @date 2022/9/18
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
import { reactive, ref, defineAsyncComponent } from 'vue';
import { UseDetailContainerOptions } from './types';

// import DetailModal from './Modal.vue';
// import DetailDrawer from './Drawer.vue';
// import DetailPage from './Page.vue';
// export { DetailModal, DetailDrawer, DetailPage };

export const DetailModal = defineAsyncComponent(() => import('./Modal.vue'));
export const DetailDrawer = defineAsyncComponent(() => import('./Drawer.vue'));
export const DetailPage = defineAsyncComponent(() => import('./Page.vue'));

// 在这里切换全局的编辑表单容器
export const DetailContainer = DetailDrawer;

/**
 * 提供基本的编辑容器配置
 * @param config
 */
export function useDetailContainer<T>(config: UseDetailContainerOptions) {
  const { containerRef, containerProps, descriptionProps, header = '', getData, onClose } = config;
  // 表单数据
  const loading = ref<boolean>(false);
  // 表单数据
  const data = ref<T>({} as T);
  // 打开弹窗是传的参数
  const paramsData = ref<any>();
  // 弹窗是否打开的
  const opened = ref<boolean>(false);
  // 容器配置
  const containerConfig = reactive({
    header: '',
    destroyOnClose: true,
    closeOnOverlayClick: true,
    confirmBtn: null,
    cancelBtn: '关闭',
    ...containerProps,
    onClose() {
      opened.value = false;
      onClose?.();
    },
  });

  const descriptionConfig = reactive({
    border: true,
    data: {},
    ...descriptionProps,
  });

  /**
   * 更新表单数据
   * @param d
   */
  function updateData(d: any) {
    d ??= {};
    data.value = d;
    descriptionConfig.data = d;
  }

  function open(params: any) {
    containerRef.value.open();
    paramsData.value = params;
    // 修改数据
    containerConfig.header = header;
    // 调用接口查询完整数据
    getData(params)
      .then((res: any) => {
        updateData(res);
      })
      .finally(() => {
        loading.value = false;
      });
    loading.value = true;
    opened.value = true;
  }

  return {
    open,
    close: containerRef.close,
    updateData,
    containerConfig,
    descriptionConfig,
    opened,
    params: paramsData,
    data,
    loading,
  };
}

export default DetailContainer;
